<template>
  <div class="payment-container fade-in">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon">
              <Money />
            </el-icon>
            在线支付
          </h2>
          <p class="page-subtitle">支持多种支付方式，安全便捷的在线缴费服务</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="refreshPayments">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
          <el-button type="success" @click="exportPaymentRecords">
            <el-icon><Download /></el-icon>
            导出记录
          </el-button>
        </div>
      </div>
    </div>

    <!-- 支付统计概览 -->
    <div class="payment-overview">
      <el-row :gutter="24">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="payment-card total" shadow="hover">
            <div class="payment-content">
              <div class="payment-icon">
                <el-icon><Money /></el-icon>
              </div>
              <div class="payment-info">
                <div class="payment-number">¥{{ totalAmount.toFixed(2) }}</div>
                <div class="payment-label">总支付金额</div>
                <div class="payment-desc">今日支付总额</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="payment-card success" shadow="hover">
            <div class="payment-content">
              <div class="payment-icon">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="payment-info">
                <div class="payment-number">{{ successCount }}</div>
                <div class="payment-label">支付成功</div>
                <div class="payment-desc">成功交易笔数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="payment-card pending" shadow="hover">
            <div class="payment-content">
              <div class="payment-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="payment-info">
                <div class="payment-number">{{ pendingCount }}</div>
                <div class="payment-label">待支付</div>
                <div class="payment-desc">等待支付订单</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="payment-card failed" shadow="hover">
            <div class="payment-content">
              <div class="payment-icon">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="payment-info">
                <div class="payment-number">{{ failedCount }}</div>
                <div class="payment-label">支付失败</div>
                <div class="payment-desc">失败交易笔数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 支付方式统计 -->
    <el-card class="payment-methods-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>支付方式统计</h3>
          <el-select v-model="timeRange" size="small" style="width: 120px">
            <el-option label="今日" value="today" />
            <el-option label="本周" value="week" />
            <el-option label="本月" value="month" />
          </el-select>
        </div>
      </template>
      <div class="payment-methods">
        <el-row :gutter="24">
          <el-col :xs="24" :sm="12" :md="6">
            <div class="method-item wechat">
              <div class="method-icon">
                <el-icon><ChatDotRound /></el-icon>
              </div>
              <div class="method-info">
                <div class="method-name">微信支付</div>
                <div class="method-amount">¥{{ wechatAmount.toFixed(2) }}</div>
                <div class="method-count">{{ wechatCount }}笔</div>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <div class="method-item alipay">
              <div class="method-icon">
                <el-icon><CreditCard /></el-icon>
              </div>
              <div class="method-info">
                <div class="method-name">支付宝</div>
                <div class="method-amount">¥{{ alipayAmount.toFixed(2) }}</div>
                <div class="method-count">{{ alipayCount }}笔</div>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <div class="method-item bank">
              <div class="method-icon">
                <el-icon><Wallet /></el-icon>
              </div>
              <div class="method-info">
                <div class="method-name">银行卡</div>
                <div class="method-amount">¥{{ bankAmount.toFixed(2) }}</div>
                <div class="method-count">{{ bankCount }}笔</div>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <div class="method-item cash">
              <div class="method-icon">
                <el-icon><Money /></el-icon>
              </div>
              <div class="method-info">
                <div class="method-name">现金</div>
                <div class="method-amount">¥{{ cashAmount.toFixed(2) }}</div>
                <div class="method-count">{{ cashCount }}笔</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 支付记录列表 -->
    <el-card class="payment-records-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>支付记录</h3>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索订单号或姓名"
              class="search-input"
              clearable
              prefix-icon="Search"
            />
            <el-select v-model="statusFilter" placeholder="状态筛选" clearable class="status-filter">
              <el-option label="全部" value="" />
              <el-option label="支付成功" value="success" />
              <el-option label="待支付" value="pending" />
              <el-option label="支付失败" value="failed" />
            </el-select>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="filteredPayments" 
        style="width: 100%" 
        :stripe="true" 
        class="payment-table">
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="name" label="报名人" width="120" />
        <el-table-column prop="competition" label="比赛项目" width="150" />
        <el-table-column prop="amount" label="支付金额" width="120">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.amount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="method" label="支付方式" width="120">
          <template #default="{ row }">
            <el-tag :type="getPaymentMethodType(row.method)" size="small">
              {{ getPaymentMethodLabel(row.method) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="支付状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="payTime" label="支付时间" width="160" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="viewPaymentDetails(row)">查看</el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="retryPayment(row)"
              v-if="row.status === 'failed'">
              重试
            </el-button>
            <el-button 
              size="small" 
              type="success" 
              @click="downloadReceipt(row)"
              v-if="row.status === 'success'">
              收据
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalPayments"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 支付详情对话框 -->
    <el-dialog 
      v-model="showPaymentDetailsDialog" 
      title="支付详情" 
      width="800px"
      :close-on-click-modal="false">
      <div class="payment-details-content" v-if="selectedPayment">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ selectedPayment.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="报名人">{{ selectedPayment.name }}</el-descriptions-item>
          <el-descriptions-item label="比赛项目">{{ selectedPayment.competition }}</el-descriptions-item>
          <el-descriptions-item label="支付金额">¥{{ selectedPayment.amount.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">
            <el-tag :type="getPaymentMethodType(selectedPayment.method)">
              {{ getPaymentMethodLabel(selectedPayment.method) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="getStatusType(selectedPayment.status)">
              {{ getStatusLabel(selectedPayment.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ selectedPayment.createTime }}</el-descriptions-item>
          <el-descriptions-item label="支付时间">{{ selectedPayment.payTime || '未支付' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ selectedPayment.remark || '无' }}</el-descriptions-item>
        </el-descriptions>

        <div class="payment-timeline">
          <h4>支付时间线</h4>
          <el-timeline>
            <el-timeline-item 
              v-for="(activity, index) in selectedPayment.timeline" 
              :key="index"
              :timestamp="activity.time"
              :type="activity.type">
              {{ activity.description }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPaymentDetailsDialog = false">关闭</el-button>
          <el-button 
            type="primary" 
            @click="retryPayment(selectedPayment)"
            v-if="selectedPayment && selectedPayment.status === 'failed'">
            重新支付
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重新支付对话框 -->
    <el-dialog 
      v-model="showRetryPaymentDialog" 
      title="重新支付" 
      width="600px"
      :close-on-click-modal="false">
      <div class="retry-payment-content" v-if="selectedPayment">
        <el-form :model="retryPaymentForm" label-width="120px">
          <el-form-item label="订单号">
            <span>{{ selectedPayment.orderNo }}</span>
          </el-form-item>
          <el-form-item label="报名人">
            <span>{{ selectedPayment.name }}</span>
          </el-form-item>
          <el-form-item label="比赛项目">
            <span>{{ selectedPayment.competition }}</span>
          </el-form-item>
          <el-form-item label="支付金额">
            <span class="amount-text">¥{{ selectedPayment.amount.toFixed(2) }}</span>
          </el-form-item>
          <el-form-item label="支付方式">
            <el-select v-model="retryPaymentForm.method" style="width: 100%">
              <el-option label="微信支付" value="wechat" />
              <el-option label="支付宝" value="alipay" />
              <el-option label="银行卡" value="bank" />
              <el-option label="现金" value="cash" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input 
              v-model="retryPaymentForm.remark" 
              type="textarea" 
              :rows="3"
              placeholder="请输入备注信息" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showRetryPaymentDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmRetryPayment">确认支付</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { 
  Money, Refresh, Download, CircleCheck, Clock, Warning,
  ChatDotRound, CreditCard, Wallet
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const timeRange = ref('today')
const searchQuery = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const showPaymentDetailsDialog = ref(false)
const showRetryPaymentDialog = ref(false)
const selectedPayment = ref(null)

// 重新支付表单
const retryPaymentForm = ref({
  method: 'wechat',
  remark: ''
})

// 模拟支付数据
const payments = ref([
  {
    id: 1,
    orderNo: 'PAY202401150001',
    name: '张三',
    competition: '2024年春季马拉松',
    amount: 150,
    method: 'wechat',
    status: 'success',
    createTime: '2024-01-15 10:30:00',
    payTime: '2024-01-15 10:35:00',
    remark: '',
    timeline: [
      { time: '2024-01-15 10:30:00', description: '创建支付订单', type: 'primary' },
      { time: '2024-01-15 10:32:00', description: '用户扫码支付', type: 'info' },
      { time: '2024-01-15 10:35:00', description: '支付成功', type: 'success' }
    ]
  },
  {
    id: 2,
    orderNo: 'PAY202401150002',
    name: '李四',
    competition: '2024年春季马拉松',
    amount: 150,
    method: 'alipay',
    status: 'success',
    createTime: '2024-01-15 11:15:00',
    payTime: '2024-01-15 11:20:00',
    remark: '',
    timeline: [
      { time: '2024-01-15 11:15:00', description: '创建支付订单', type: 'primary' },
      { time: '2024-01-15 11:18:00', description: '用户确认支付', type: 'info' },
      { time: '2024-01-15 11:20:00', description: '支付成功', type: 'success' }
    ]
  },
  {
    id: 3,
    orderNo: 'PAY202401150003',
    name: '王五',
    competition: '2024年春季马拉松',
    amount: 150,
    method: 'bank',
    status: 'pending',
    createTime: '2024-01-15 14:20:00',
    payTime: null,
    remark: '等待银行处理',
    timeline: [
      { time: '2024-01-15 14:20:00', description: '创建支付订单', type: 'primary' },
      { time: '2024-01-15 14:25:00', description: '提交银行处理', type: 'info' }
    ]
  },
  {
    id: 4,
    orderNo: 'PAY202401150004',
    name: '赵六',
    competition: '2024年春季马拉松',
    amount: 150,
    method: 'wechat',
    status: 'failed',
    createTime: '2024-01-15 16:45:00',
    payTime: null,
    remark: '网络超时',
    timeline: [
      { time: '2024-01-15 16:45:00', description: '创建支付订单', type: 'primary' },
      { time: '2024-01-15 16:50:00', description: '支付超时', type: 'danger' }
    ]
  }
])

// 计算属性
const filteredPayments = computed(() => {
  let filtered = payments.value

  // 搜索过滤
  if (searchQuery.value) {
    filtered = filtered.filter(payment => 
      payment.orderNo.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      payment.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }

  // 状态过滤
  if (statusFilter.value) {
    filtered = filtered.filter(payment => payment.status === statusFilter.value)
  }

  return filtered
})

const totalPayments = computed(() => filteredPayments.value.length)

const totalAmount = computed(() => {
  return payments.value
    .filter(p => p.status === 'success')
    .reduce((sum, p) => sum + p.amount, 0)
})

const successCount = computed(() => 
  payments.value.filter(p => p.status === 'success').length
)

const pendingCount = computed(() => 
  payments.value.filter(p => p.status === 'pending').length
)

const failedCount = computed(() => 
  payments.value.filter(p => p.status === 'failed').length
)

const wechatAmount = computed(() => {
  return payments.value
    .filter(p => p.method === 'wechat' && p.status === 'success')
    .reduce((sum, p) => sum + p.amount, 0)
})

const wechatCount = computed(() => 
  payments.value.filter(p => p.method === 'wechat' && p.status === 'success').length
)

const alipayAmount = computed(() => {
  return payments.value
    .filter(p => p.method === 'alipay' && p.status === 'success')
    .reduce((sum, p) => sum + p.amount, 0)
})

const alipayCount = computed(() => 
  payments.value.filter(p => p.method === 'alipay' && p.status === 'success').length
)

const bankAmount = computed(() => {
  return payments.value
    .filter(p => p.method === 'bank' && p.status === 'success')
    .reduce((sum, p) => sum + p.amount, 0)
})

const bankCount = computed(() => 
  payments.value.filter(p => p.method === 'bank' && p.status === 'success').length
)

const cashAmount = computed(() => {
  return payments.value
    .filter(p => p.method === 'cash' && p.status === 'success')
    .reduce((sum, p) => sum + p.amount, 0)
})

const cashCount = computed(() => 
  payments.value.filter(p => p.method === 'cash' && p.status === 'success').length
)

// 方法
const refreshPayments = () => {
  ElMessage.success('支付数据已刷新')
}

const exportPaymentRecords = () => {
  ElMessage.success('支付记录导出成功')
}

const viewPaymentDetails = (row) => {
  selectedPayment.value = row
  showPaymentDetailsDialog.value = true
}

const retryPayment = (row) => {
  selectedPayment.value = row
  retryPaymentForm.value = {
    method: 'wechat',
    remark: ''
  }
  showRetryPaymentDialog.value = true
}

const confirmRetryPayment = () => {
  const payment = selectedPayment.value
  payment.method = retryPaymentForm.value.method
  payment.status = 'success'
  payment.payTime = new Date().toLocaleString()
  payment.timeline.push({
    time: payment.payTime,
    description: `重新支付成功 (${getPaymentMethodLabel(retryPaymentForm.value.method)})`,
    type: 'success'
  })
  showRetryPaymentDialog.value = false
  ElMessage.success('重新支付成功')
}

const downloadReceipt = (row) => {
  ElMessage.success('收据下载成功')
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const getPaymentMethodType = (method) => {
  const types = {
    wechat: 'success',
    alipay: 'primary',
    bank: 'warning',
    cash: 'info'
  }
  return types[method] || 'info'
}

const getPaymentMethodLabel = (method) => {
  const labels = {
    wechat: '微信支付',
    alipay: '支付宝',
    bank: '银行卡',
    cash: '现金'
  }
  return labels[method] || method
}

const getStatusType = (status) => {
  const types = {
    success: 'success',
    pending: 'warning',
    failed: 'danger'
  }
  return types[status] || 'info'
}

const getStatusLabel = (status) => {
  const labels = {
    success: '支付成功',
    pending: '待支付',
    failed: '支付失败'
  }
  return labels[status] || status
}

onMounted(() => {
  console.log('在线支付页面已加载')
})
</script>

<style scoped>
.payment-container {
  padding: var(--spacing-lg);
  background: var(--bg-primary);
  min-height: 100vh;
}

.page-header {
  margin-bottom: var(--spacing-xl);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--spacing-lg);
}

.title-section {
  flex: 1;
}

.page-title {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  font-size: 1.75rem;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 var(--spacing-sm) 0;
}

.title-icon {
  font-size: 1.5rem;
  color: var(--primary-color);
}

.page-subtitle {
  color: var(--text-secondary);
  font-size: 0.9rem;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: var(--spacing-md);
}

/* 支付概览 */
.payment-overview {
  margin-bottom: var(--spacing-xl);
}

.payment-card {
  border-radius: var(--radius-lg);
  transition: all 0.3s ease;
}

.payment-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
}

.payment-content {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
}

.payment-icon {
  width: 60px;
  height: 60px;
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  color: white;
  transition: all 0.3s ease;
}

.payment-card.total .payment-icon {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
}

.payment-card.success .payment-icon {
  background: linear-gradient(135deg, var(--success-color), var(--success-dark));
}

.payment-card.pending .payment-icon {
  background: linear-gradient(135deg, var(--warning-color), var(--warning-dark));
}

.payment-card.failed .payment-icon {
  background: linear-gradient(135deg, var(--danger-color), var(--danger-dark));
}

.payment-info {
  flex: 1;
}

.payment-number {
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.payment-label {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.payment-desc {
  color: var(--text-secondary);
  font-size: 0.8rem;
}

/* 支付方式统计 */
.payment-methods-card {
  margin-bottom: var(--spacing-xl);
  border-radius: var(--radius-lg);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: var(--text-primary);
  font-size: 1.1rem;
  font-weight: 600;
}

.payment-methods {
  padding: var(--spacing-lg) 0;
}

.method-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  padding: var(--spacing-lg);
  border-radius: var(--radius-lg);
  background: var(--bg-secondary);
  transition: all 0.3s ease;
}

.method-item:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.method-icon {
  width: 50px;
  height: 50px;
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.25rem;
  color: white;
}

.method-item.wechat .method-icon {
  background: linear-gradient(135deg, #07c160, #06ad56);
}

.method-item.alipay .method-icon {
  background: linear-gradient(135deg, #1677ff, #0958d9);
}

.method-item.bank .method-icon {
  background: linear-gradient(135deg, var(--warning-color), var(--warning-dark));
}

.method-item.cash .method-icon {
  background: linear-gradient(135deg, var(--success-color), var(--success-dark));
}

.method-info {
  flex: 1;
}

.method-name {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.method-amount {
  font-size: 1.1rem;
  font-weight: 600;
  color: var(--primary-color);
  margin-bottom: var(--spacing-xs);
}

.method-count {
  color: var(--text-secondary);
  font-size: 0.9rem;
}

/* 支付记录 */
.payment-records-card {
  border-radius: var(--radius-lg);
}

.header-actions {
  display: flex;
  gap: var(--spacing-md);
}

.search-input {
  width: 200px;
}

.status-filter {
  width: 120px;
}

.payment-table {
  margin-bottom: var(--spacing-lg);
}

.amount-text {
  font-weight: 600;
  color: var(--primary-color);
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: var(--spacing-lg);
}

/* 详情对话框 */
.payment-details-content {
  padding: var(--spacing-lg) 0;
}

.payment-timeline {
  margin-top: var(--spacing-xl);
}

.payment-timeline h4 {
  margin: 0 0 var(--spacing-lg) 0;
  color: var(--text-primary);
  font-size: 1rem;
  font-weight: 600;
}

/* 重新支付对话框 */
.retry-payment-content {
  padding: var(--spacing-lg) 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .payment-container {
    padding: var(--spacing-md);
  }

  .header-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .payment-content {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-md);
  }

  .payment-icon {
    width: 50px;
    height: 50px;
    font-size: 1.25rem;
  }

  .method-item {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-md);
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-md);
  }

  .header-actions {
    width: 100%;
    flex-direction: column;
  }

  .search-input,
  .status-filter {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 1.5rem;
  }

  .payment-number {
    font-size: 1.25rem;
  }
}
</style>
